

import 'dart:async';
import 'dart:io';
import 'package:httpplugin/httpplugin.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

class AppCacheManager with CacheBase{

  late SharedPreferences _preferences;

  Future<void> cacheInitialize() async{
    _preferences = await SharedPreferences.getInstance();
  }

  @override
  String getValueForKey(String key) {
    // TODO: implement getValueForKey
    return "";
  }

  @override
  void setValueForKey(String key, String value) {
    // TODO: implement setValueForKey
  }

  /// 加载缓存大小
  Future<_CacheEntity> loadCacheSize() async{
    /// 获取临时文件路径
    Directory tempDir = await getTemporaryDirectory();
    /// 获取临时文件的大小
    double size = await _getSize(tempDir);
    /// 返回临时文件大小格式转换
    return renderSize(size);
  }

  /// 递归获取所有文件
  Future<double> _getSize(FileSystemEntity file) async{
    if (file is File) {
      int length = await file.length();
      return length.toDouble();
    } else if (file is Directory) {
      if (file.path.endsWith("libCachedImageData")) {
        return 0;
      }
      /// 文件路径下面的所有文件
      final Iterator<FileSystemEntity> children = file.listSync().iterator;
      double total = 0;
      while(children.moveNext()) {
        FileSystemEntity entity = children.current;
        /// 递归获取
        total += await _getSize(entity);
      }
      return total;
    }
    return 0;
  }

  /// 计算文件大小
  _CacheEntity renderSize(double? size) {
    List<String> unit = ["B", "K", "M", "G"];
    if (size == null) {
      return _CacheEntity(cacheSize: 0, unit: unit[0]);
    } else {
      int index = 0;
      while (size! > 1024) {
        index ++;
        size = size / 1024;
      }
      /// 保留两位小数
      double value = (size * 100).ceil() / 100;
      /// 返回模型
      return _CacheEntity(unit: unit[index], cacheSize: value);
    }
  }

  /// 清除缓存
  Future<void> clearCache() async{
    Directory tempDir = await getTemporaryDirectory();
    await _delDir(tempDir);
  }

  /// 递归删除文件
  Future<void> _delDir(FileSystemEntity file) async{
    if (file is Directory) {
      if (file.path.endsWith("libCachedImageData")) {
        return;
      }
      /// 获取文件路径下所有文件
      Iterator<FileSystemEntity> iterator = file.listSync().iterator;
      while (iterator.moveNext()) {
        FileSystemEntity entity = iterator.current;
        /// 递归删除
        await _delDir(entity);
      }
    }
    try {
      /// 删除文件夹
      await file.delete();
    }catch(e){
      print("delete error $e");
    }
  }
}

class _CacheEntity {
  _CacheEntity({this.cacheSize = 0, this.unit = "B"});
  /// 缓存大小
  final double cacheSize;
  /// 缓存大小单位
  final String unit;
}